package service;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.jfinal.plugin.activerecord.Db;
import common.model.User;
import util.IDUtil;

import java.io.File;
import java.util.*;

public class UserService extends DbRealmService<User> {

    public User getByEmail(String email){
        return new User().findFirst("select * from user where email=?",email);
    }

    public int importFromFile(File file){
        ExcelReader reader= ExcelUtil.getReader(file);
        List<Map<String,Object>> datas=reader.readAll();
        List<User> dbDatas=new ArrayList<>();
        Iterator<Map<String,Object>> iterator=datas.iterator();
        while(iterator.hasNext()){
            Map<String,Object> data=iterator.next();
            User user=new User();
            user.setId(IDUtil.getRandomID());
            user.setPassword("123456");
            user.setRole("user");
            user.setEmail(data.get("邮箱").toString());
            user.setName(data.get("姓名").toString());
            user.setWhen(new Date());
            dbDatas.add(user);
        }
        int[] results=Db.batchSave(dbDatas,1000);
        int sum=0;
        for(int i=0;i<results.length;i++){
            sum+=results[i];
        }
        System.out.println(sum);
        return sum;
    }
}
